package io.kubesphere.devops.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class SpringContextUtils {

    /**
     * spring 上下文
     */
    private static ApplicationContext applicationContext;

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(SpringContextUtils.class);

    /**
     * 注入ApplicationContext
     *
     * @param context
     */
    public static void setContext(ApplicationContext context) {
        SpringContextUtils.applicationContext = context;
    }

    /**
     * 实现父类的setApplicationContext方法注入ApplicationContext
     */
    public void setApplicationContext(ApplicationContext context) {
        if (log.isDebugEnabled()) {
            log.debug("SpringContextUtil init applicaitonContext");
        }
        SpringContextUtils.setContext(context);
    }

    /**
     * 获取ApplicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        checkContext();
        return applicationContext;
    }

    /**
     * 获取Bean
     *
     * @param name
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) getApplicationContext().getBean(name);
    }

    /**
     * 判断是否加载ApplicationContext
     *
     * @return
     */
    private static boolean hasLoadContext() {
        return applicationContext != null;
    }

    private static void checkContext() {
        if (!hasLoadContext()) {
            throw new IllegalStateException("SpringContextUtils初始化失败,需要定义SpringContextUtils");
        }
    }

    /**
     * 是否包含名称为name的bean
     *
     * @param name
     * @return
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
}
